<!-- 顶部栏模块 -->
<template>
    <div class="page-header">
        <span class="page-title">
            <template v-if="$slots['header-left']">
                <slot name="header-left"></slot>
            </template>
            <template v-else>
                <template v-if="globalOptions.title">
                    <img src="../../common/style/logo.png" class="page-title-icon" alt="">
                    {{ globalOptions.title }}
                </template>
            </template>
        </span>

        <!-- 操作画布区域 -->
        <div class="page-header-tool">
            <div class="tool-left">
                <ul class="tool-list">
                    <input type="file" name="jsonDataFile" id="jsonDataFile" :hidden="true" accept=".json,.txt"
                        @change="importJsonData">
                    <template v-for="(item,index) in actionData">
                        <a-tooltip placement="bottom">
                            <template #title>
                                <span class="small-text">{{item.title}}</span>
                            </template>
                            <li @click="item.on" :class="{disabled: item.disabled}" v-if="item.show">
                                <dc-icon :icon="item.icon" className="tool-icon"></dc-icon>
                            </li>
                        </a-tooltip>
                    </template>
                </ul>
            </div>
            <div class="tool-right">
                <ul class="tool-list">
                    <template v-for="item in pageTypeList">
                        <a-tooltip placement="bottom">
                            <template #title>
                                <span class="small-text">{{item.name}}</span>
                            </template>
                            <template v-if="globalOptions.changePageType">
                                <li :class="item.active?'active':''" @click="pageTypeItemClick(item)">
                                    <dc-icon :icon="item.icon"></dc-icon>
                                </li>
                            </template>
                        </a-tooltip>
                    </template>
                </ul>
            </div>
        </div>

        <div class="page-header-btn">
            <template v-if="$slots['header-right']">
                <slot name="header-right"></slot>
            </template>
            <template v-else>
                <!-- <a-button @click="handleTestShowData">
                    查看数据
                </a-button> -->
                <a-button @click="previewPage" type="primary" v-if="globalOptions.preview">
                    <template #icon>
                        <FileSearchOutlined />
                    </template>
                    预览
                </a-button>
            </template>
        </div>
    </div>
</template>

<script setup>
import { reactive, computed, createVNode, useSlots } from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { setImportJsonData, generateData, globalOptions } from '../../pageManager.js'
import { revoke } from '../../common/util/revoke.js'

const emit = defineEmits(['handleTestShowData', 'viewJsonData', 'previewPage', 'changeScale', 'changePageType', 'resetEditPanel', 'clearActiveItem', 'handleResetSelectItem'])

const data = reactive({
    // 页面类型
    pageTypeList: [
        {
            type: 1,
            icon: "DesktopOutlined",
            name: "PC",
            active: false,
            value: 'pc'
        },
        {
            type: 2,
            icon: "TabletOutlined",
            name: "平板",
            active: false,
            value: 'ipad'
        },
        {
            type: 3,
            icon: "MobileOutlined",
            name: "手机",
            active: false,
            value: 'mobile'
        }
    ],
})

// 操作
const actionData = computed(() => {
    return [
        {
            title: "查看源码",
            icon: "CodeOutlined",
            on: () => viewJsonData(),
            show: globalOptions.sourceCode
        },
        {
            title: "历史记录",
            icon: "FieldTimeOutlined",
            on: () => viewHistory(),
            show: globalOptions.history
        },
        {
            title: "导入",
            icon: "UploadOutlined",
            on: () => importJsonDataClick(),
            show: globalOptions.import
        },
        {
            title: "清空",
            icon: "DeleteOutlined",
            on: () => resetEditPanel(),
            show: globalOptions.clear,
            disabled: !generateData.data.children.length
        },
        {
            title: "撤销",
            icon: "LeftOutlined",
            on: () => handleUndo(),
            show: globalOptions.revoke,
            disabled: !revoke.recordList.value.length
        },
        {
            title: "重做",
            icon: "RightOutlined",
            on: () => handleRedo(),
            show: globalOptions.revoke,
            disabled: !revoke.undoList.value.length
        },
    ]
})


const pageTypeList = computed(() => {
    let list = [];
    // 页面类型的选项
    let pageTypeData = globalOptions.pageTypeData;
    for (let i = 0; i < pageTypeData.length; i++) {
        let pageTypeItem = pageTypeData[i];
        for (let j = 0; j < data.pageTypeList.length; j++) {
            let item = data.pageTypeList[j];
            if (pageTypeItem == item.value) {
                list.push(item);
            }
        }
    }

    // 选中的页面类型
    let pageTypeActive = globalOptions.selectPageType;
    for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (item.value == pageTypeActive) {
            item.active = true;
        }
    }

    return list;
})



/**
 * @desc 获取页面类型列表
 */
const getPageTypeList = () => {
    // data.pageTypeList
    globalOptions.pageTypeData;
}

/**
 * @method
 * @desc 点击测试按钮
 */
const handleTestShowData = () => {
    emit("handleTestShowData");
}


/**
 * @method
 * @desc 查看源码
 */
const viewJsonData = () => {
    emit("viewJsonData");
    revoke.addHistory(null, "查看源码");
}

/**
 * @method
 * @desc 查看历史操作记录
 */
const viewHistory = () => {
    emit("viewHistory");
}


/**
 * @method
 * @desc 预览页面
 */
const previewPage = () => {
    emit("previewPage");
    revoke.addHistory(null, "预览页面");
}


/**
 * @method
 * @param {Object} item 当前组件的对象数据
 * @desc 选中页面类型，将选中的值传递至顶层dcPageDesigner中的changePageType函数中
 */
const pageTypeItemClick = (item) => {
    data.pageTypeList.forEach(item => {
        item.active = false;
    });
    item.active = true;

    // generateData.data.children.reverse()
    // setTimeout(() => {
    //     generateData.data.children.reverse()
    // }, 100);

    revoke.addHistory(null, `画布切换至【${item.name}】模式`);
    emit("changePageType", item.value);
}

/**
 * @method
 * @desc 清空画布
 */
const resetEditPanel = () => {

    if (generateData.data.children.length < 1) return;

    if (globalOptions.clearConfirm) {
        Modal.confirm({
            title: '确定要清空画布吗?',
            icon: createVNode(ExclamationCircleOutlined),
            cancelText: "取消",
            okText: "确认",
            // content: createVNode('div', { style: 'color:red;font-size:12px' }, '此操作将不可撤销'),
            onOk() {
                emit("resetEditPanel");
                message.success(`清空画布操作成功`);
                revoke.add(generateData.data, '清空画布')
            },
            onCancel() {
            },
        });
    } else {
        emit("resetEditPanel");
        message.success(`清空画布操作成功`);
        revoke.add(generateData.data, '清空画布')
    }


}

// 打开上传文件的窗口
const importJsonDataClick = () => {
    document.getElementById("jsonDataFile").click();
}

// 导入json数据
const importJsonData = (e) => {

    const file = e.target.files[0];

    if (!file) {
        return;
    }
    const reader = new FileReader();
    reader.onload = function (e) {
        const content = e.target.result;
        try {
            setImportJsonData(JSON.parse(content), () => {
                resetActive();
                message.success("JSON数据导入成功")
                revoke.add(generateData.data, '导入JSON文件')
            });
        } catch (e) {
            message.error("导入失败，请检查json数据格式");
        }

    };
    reader.readAsText(file);
    // 必须将内容置空，否则第二次上传相同文件则会失效
    e.target.value = ''
}

/**
 * @desc 撤销
 */
const handleUndo = () => {
    let undoData = revoke.undo();
    // console.log("撤销", undoData);
    if (undoData) {
        generateData.data = undoData;
        resetActive();
    }
}

/**
 * @desc 重做
 */
const handleRedo = () => {
    let redoData = revoke.redo();
    // console.log("重做", redoData);
    if (redoData) {
        generateData.data = redoData;
        resetActive();
    }
}

/**
 * @desc 重置选中
 */
const resetActive = () => {
    emit("clearActiveItem");
    emit("handleResetSelectItem");
}


</script>

<style lang="less" scoped>
.jsonDataFileBtn {
    cursor: pointer;
}
</style>